import { ApiResponse, Article, Channel } from '@/types/data'
import { HomeAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import {
  getLocalChannels,
  getToken,
  hasToken,
  setLocalChannels,
} from '@/utils/storage'

type ChanRes = { channels: Channel[] }
export const getUserChannels = (): RootThunkAction => {
  return async (dispatch) => {
    // 如果用户是登陆,实时获取登录获取的频道数据
    const token = getToken().token
    if (token) {
      const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
        '/user/channels'
      )
      // console.log(res)
      dispatch({
        type: 'home/getUserChannels',
        payload: res.data.data.channels,
      })
    } else {
      // 游客身份,尝试从本地获取频道数据
      const channels = getLocalChannels()
      if (channels.length > 0) {
        // 1.如果本地拿到了,直接用(不需要发请求)
        dispatch({
          type: 'home/getUserChannels',
          payload: channels,
        })
      } else {
        // 2.如果本地没拿到,首次访问,发送请求拿默认的频道列表,且存本地
        const res = await request.get<ApiResponse<ChanRes>>('/user/channels')
        dispatch({
          type: 'home/getUserChannels',
          payload: res.data.data.channels,
        })
        setLocalChannels(res.data.data.channels)
      }
    }
  }
}

export const getAllChannels = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
      '/channels'
    )
    // console.log(res)

    dispatch({
      type: 'home/getAllChannels',
      payload: res.data.data.channels,
    })
  }
}

export const changeActive = (id: number): HomeAction => {
  return {
    type: 'home/changeActive',
    payload: id,
  }
}

// 删除
export const delChannel = (id: number): RootThunkAction => {
  return async (dispatch, getState) => {
    const { userChannels } = getState().home
    if (hasToken()) {
      // 用户登录了，发送请求进行删除
      await request.delete('/user/channels', {
        data: {
          channels: [id],
        },
      })
    } else {
      // 如果没有登录，本地删除一条数据
      setLocalChannels(userChannels.filter((item) => item.id !== id))
    }
    // 重新渲染
    dispatch(getUserChannels())
  }
}

// 添加
export const addChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    // 获取到所有的userChannels
    const { userChannels } = getState().home
    // 如果登录了，发送请求获取频道信息
    if (hasToken()) {
      await request.patch('/user/channels', {
        channels: [channel],
      })
    } else {
      // 如果没有登录，将频道数据保存到本地
      // 将channels数据保存本地
      setLocalChannels([...userChannels, channel])
    }
    dispatch(getUserChannels())
  }
}

// 首页频道数据
type GetArtRes = ApiResponse<{
  pre_timestamp: string
  results: Article[]
}>

export const getArticles = (
  channel_id: number,
  timestamp: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<GetArtRes>('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })
    // console.log(res)
    dispatch({
      type: 'home/saveChannelArticles',
      payload: {
        channel_id,
        articles: res.data.data.results,
        timestamp: res.data.data.pre_timestamp,
      },
    })
  }
}

export const getArticlesRefresh = (
  channel_id: number,
  timestamp: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<
      ApiResponse<{
        pre_timestamp: string
        results: Article[]
      }>
    >('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })
    const { pre_timestamp, results } = res.data.data
    dispatch({
      type: 'home/refreshChannelArticles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      },
    })
  }
}
